package com.lagou.edu.notice.service;

import com.corundumstudio.socketio.Configuration;
import com.corundumstudio.socketio.SocketIOClient;
import com.corundumstudio.socketio.listener.ConnectListener;
import com.corundumstudio.socketio.listener.DisconnectListener;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

@Component
public class MsgService {

    private static List<SocketIOClient> clients = new ArrayList<SocketIOClient>();

    static {
        Configuration config = new Configuration();
        config.setHostname("localhost");
        config.setPort(9898);


        final com.corundumstudio.socketio.SocketIOServer server = new com.corundumstudio.socketio.SocketIOServer(config);
        // 添加创建连接的监听器
        server.addConnectListener(new ConnectListener() {
            @Override
            public void onConnect(SocketIOClient client) {
                clients.add(client);
            }
        });

        // 添加断开连接的监听器
        server.addDisconnectListener(new DisconnectListener() {
            @Override
            public void onDisconnect(SocketIOClient client) {
                clients.remove(client);
            }
        });

        // 启动服务
        server.start();
    }

    public void push(String msg) {
        for (SocketIOClient client : clients) {
            client.sendEvent("hello", msg);
        }
    }
}
